package com.test.mess;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Scanner;

public class JavaDownloadSingalFileFromURL {

    private static LocalDate now = LocalDate.now();
    private static String date = now.format(DateTimeFormatter.ofPattern("yy-MM"));
    private static String baseDir = "D:\\dl\\" + date;

    public static void main(String[] args) {
        if (args== null || args.length != 2) {
            System.out.println("参数错误：参数1-url；参数2-文件名");
            return;
        }
        String imageUrl = args[0];
        String fileName = args[1];
        try {
            downloadUsingNIO(imageUrl, baseDir + fileName);
            // downloadUsingStream(url, "D:/users/maxsu/sitemap_stream.xml");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void downloadUsingStream(String urlStr, String file) throws IOException {
        URL url = new URL(urlStr);
        BufferedInputStream bis = new BufferedInputStream(url.openStream());
        FileOutputStream fis = new FileOutputStream(file);
        byte[] buffer = new byte[1024];
        int count = 0;
        while ((count = bis.read(buffer, 0, 1024)) != -1) {
            fis.write(buffer, 0, count);
        }
        fis.close();
        bis.close();
    }

    private static void downloadUsingNIO(String urlStr, String file) {
        try {
            URL url = new URL(urlStr);
            ReadableByteChannel rbc = Channels.newChannel(url.openStream());
            FileOutputStream fos = new FileOutputStream(file);
            fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
            fos.close();
            rbc.close();
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

}

